package admin

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"src/global"
	websocket2 "src/handler/websocket"
	"src/model"
	"src/model/ProtoModel"
	service2 "src/service"
)

type Bind struct {
}

var Indexs *Bind

func NewBind() *Bind {
	return &Bind{}
}

// 绑定房间
func (*Bind) BindRoom(b *service2.Req) {
	var err error
	// 接收post参数
	body, err := ioutil.ReadAll(b.R.Body)
	if err != nil {
		log.Println(err)
		b.Fail("读取body失败")
		return
	}
	//var reg model.LoginModelReg
	userBind := model.RoomBindModel{}
	err = json.Unmarshal(body, &userBind)
	if err != nil {
		b.Fail("json格式失败")
		return
	}
	err = (&websocket2.WebSocketService{}).BindRoom(&userBind)
	//json.Unmarshal(userBind, &redata)
	if err != nil {
		log.Println(err)
		b.Fail(err.Error())
		return
	}
	b.Ok("成功")
}

// 退出房间
func (*Bind) OutRoom(b *service2.Req) {

	var err error
	// 接收post参数
	body, err := ioutil.ReadAll(b.R.Body)
	if err != nil {
		log.Println(err)
	}
	//var reg model.LoginModelReg
	userBind := model.RoomBindModel{}
	err = json.Unmarshal(body, &userBind)
	if err != nil {
		return
	}

	reply := &ProtoModel.ReplyBodyProto{
		Key:  "room_out",
		Code: "200",
		Data: make(map[string]string),
	}
	//global.Ws_.
	cons := global.Ws_.UserList[userBind.Uid]
	if cons != nil {
		for _, connId := range cons {
			conn := global.Ws_.ConnList[connId]
			if conn.RoomNo != "" && global.Ws_.RoomList[conn.RoomNo] != nil && global.Ws_.RoomList[conn.RoomNo][connId] != "" {
				delete(global.Ws_.RoomList[conn.RoomNo], conn.Id)
				reply.Code = "200"
				reply.Data["msg"] = "您已退出房间"
				reply.Data["uid"] = conn.Uid

				(&service2.ReplyBody{}).SendMsgToConn(reply, conn.Id)
				var messageProto ProtoModel.MessageProto
				messageProto.Action = "user_out_room"
				messageProto.Title = "房间消息"
				messageProto.Content = make(map[string]string)
				messageProto.Content["roomNo"] = conn.RoomNo
				messageProto.Content["uid"] = conn.Uid
				messageProto.Content["nickname"] = conn.Nickname
				messageProto.Content["avatar"] = conn.Avatar
				messageProto.Content["msg"] = conn.Nickname + "退出房间"
				(&service2.Message{}).SendMsgToRoom(&messageProto, conn.RoomNo)
				global.Ws_.ConnList[connId].RoomNo = ""
			}
		}
		b.Ok("成功")
	}
	b.Fail("链接不存在")
}
func (*Bind) BindUser(b *service2.Req) {
	// 接收post参数
	body, err := ioutil.ReadAll(b.R.Body)
	if err != nil {
		log.Println(err)
	}
	//var reg model.LoginModelReg
	userBind := model.UserBindProto{}
	json.Unmarshal(body, &userBind)

	err = (&websocket2.WebSocketService{}).BindUser(&userBind)
	//json.Unmarshal(userBind, &redata)
	if err != nil {
		log.Println(err)
		b.Fail(err.Error())
		return
	}
	b.Ok("绑定成功")

}
